package com.qf.commons.web.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import com.qf.commons.data.result.R;
import com.qf.commons.data.result.RCodes;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author YaoJiXing
 * created 2022/8/30 14:30
 */
@Slf4j
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
        log.error("[sentinel exception] 发生了sentinel异常！");
        R result = null;

        if (e instanceof FlowException) {
            result = R.createFail(RCodes.FLOW_ERROR);
        } else if (e instanceof DegradeException) {
            result = R.createFail(RCodes.DEGRADE_ERROR);
        } else {
            result = R.createFail(RCodes.FAIL);
        }

        //response.setStatus(500);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(JSON.toJSONString(result));
        response.getWriter().close();
    }
}
